package com.cheng.service.FaceService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheng.mapper.ClassMapper;
import com.cheng.mapper.UserMapper;
import com.cheng.pojo.*;
import com.cheng.utli.DateTime;
import com.cheng.utli.RedisUtil;
import com.cheng.utli.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.cheng.controller.Constant.*;
import static com.cheng.service.FaceService.UserServiceConstant.*;
@Service
public class StudentServiceImpl implements StudentService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private RedisUtil redisUtil;
    private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);
    @Override
    public JSONObject getClassInfo(String openId, String cid) {
        JSONObject result = new JSONObject();
        ClassRecord classInfo = classMapper.getClassInfo(cid);

        if(classInfo ==null){

            return null;
        }
        User user = userMapper.getUser(openId);

        //判断用户是否添加到该表
        if(classMapper.checkUser(cid,user.getSid())>0){
            result.put("hasAdd","yes");
            return result;
        }


        //根据tid获取tname
        Teacher teacher = userMapper.getTeacherTid(classInfo.getTid());
        logger.info("teacher>>>>>>>>>"+teacher);
        result.put("tname",teacher.getName());
        result.put("name",classInfo.getcName());
        result.put("introduce",classInfo.getIntroduce());
        //得到班级人数
        result.put("num",classMapper.getClassNum(cid));
        return result;
    }

    @Override
    public String joinClass(String openId,String cid) {
        User user = userMapper.getUser(openId);

        //判断用户是否添加到该表
        if(classMapper.checkUser(cid,user.getSid())>0){
            return "用户已经添加到该表";
        }

        HashMap<String,String> info = new HashMap<String,String>();
        info.put("userId",user.getSid());
        info.put("name",user.getName());
        info.put("cid",cid);
        info.put("power","2");
        info.put("state","0");

        //将学生的信息加入班级表
        classMapper.joinClass(info);
        return "添加成功";
    }

    @Override
    public void updateSignInfo(String openId, String cid) {
        //根据openId得到sid
        User user = userMapper.getUser(openId);


        String key = redisUtil.formatRedisKey(CLASS_SIGN_NUMBER,cid);

        String number = (String) redisUtil.get(key);

        HashMap userInfo = new HashMap<String,String>();

        userInfo.put("sid",user.getSid());
        userInfo.put("cid",cid);
        userInfo.put("number",number);

        classMapper.updateSignInfo(userInfo);
    }

    @Override
    public JSONObject getUserSignInfo(String cid) {
        JSONObject result = new JSONObject();
        JSONObject userInfo = new JSONObject();
        JSONArray userArray = new JSONArray();

        String key = redisUtil.formatRedisKey(CLASS_SIGN_NUMBER,cid);
        String number = (String) redisUtil.get(key);

        return queryClassDetailSignInfo(cid,number);
    }
    /**
     *获取某一次的具体信息
     * @param cid
     * @param number
     * @return
     */
    public JSONObject queryClassDetailSignInfo(String cid ,String number){
        JSONObject userInfo = new JSONObject();
        JSONArray signArray = new JSONArray();
        JSONArray noSignArray = new JSONArray();
        JSONArray leaveArray = new JSONArray();


        //根据cid，number得到本次签到信息
        List<SignIn> SignInfo =  classMapper.getUserSignInfo(cid,number);

        for (SignIn signIn:SignInfo) {
            userInfo.put("name",signIn.getName());
            userInfo.put("signInTime",signIn.getSignInTime());
            userInfo.put("sid",signIn.getcName());
            userInfo.put("state",signIn.getState());
            if(signIn.getState().equals(SIGN)){
                signArray.add(userInfo);
            }else if(signIn.getState().equals(NOSIGN)){
                noSignArray.add(userInfo);
            }else if(signIn.getState().equals(LEAVE)){
                leaveArray.add(userInfo);
            }
        }
        JSONObject result = new JSONObject();
        result.put("signInfo",signArray);
        result.put("noSignInfo",noSignArray);
        result.put("leaveInfo",leaveArray);

        return result;
    }

    /**
     *
     * 根据cid和openId获得该同学的在本次课程的签到记录
     *
     * */
    @Override
    public JSONObject queryClassSignInInfo(String cid, String openId) {
        JSONObject result = new JSONObject();

        JSONArray signInfoArray = new JSONArray();


        //根据openId得到sid
        User user = userMapper.getUser(openId);

        List<SignIn> SignInfo =classMapper.queryClassSignInInfo(user.getSid(),cid);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
        for (SignIn signInfo:
                SignInfo) {
            JSONObject oneSignInfo = new JSONObject();
            oneSignInfo.put("name",signInfo.getName());
            oneSignInfo.put("signInTime",sdf.format(new java.sql.Date(signInfo.getSignInTime().getTime())));
            oneSignInfo.put("sid",signInfo.getcName());
            oneSignInfo.put("number",signInfo.getNumber());
            oneSignInfo.put("state",signInfo.getState());
            signInfoArray.add(oneSignInfo);
        }

        result.put("cidSignInfo",signInfoArray);

        return result;
    }

    @Override
    public JSONObject getUserAllLeaveInfo(String openId,String cid) {
        User user = userMapper.getUser(openId);
        String sid = user.getSid();
        List<LeaveInfo> leaveInfos = userMapper.getUserAllLeaveInfo(sid,cid);

        JSONObject returnObj = new JSONObject();
        returnObj.put("list",leaveInfos);
        return returnObj;
    }

    /**
     * 添加请假信息进入用户表
     * @param map
     * @return
     */
    @Override
    public void userLeaveHandler(HashMap<String,String> map) {
        //通过openid得到sid
        User user = userMapper.getUser(map.get("openId"));

        map.remove("openId");
        map.put("sid",user.getSid());
        map.put("state","0");
        map.put("name",user.getName());
        String today = DateTime.getTimestamp("yyyyMMdd");
        map.put("today",today);
        String logId = Utils.randomString().substring(0,12);
        map.put("logId",logId);
        userMapper.userLeaveHandler(map);

        // 添加请假记录表到下一次签到记录
        String cid = map.get("cid");
        String key = redisUtil.formatRedisKey(CLASS_SIGN_NUMBER,cid);

        ClassRecord classInfo = classMapper.getClassInfo(cid);

        int number = 1 ;
        if(redisUtil.exists(key)){
            number = Integer.parseInt((String) redisUtil.get(key)) +1;
            logger.info("当前得到班级签到次数为:"+number);
        }
        HashMap<String,String> singInfo = new HashMap<String,String>();
        //入签到表参数
        singInfo.put("cid",cid);
        singInfo.put("cname",classInfo.getcName());
        singInfo.put("sid",user.getSid());
        singInfo.put("name",user.getName());
        singInfo.put("date",today);
        singInfo.put("number", String.valueOf(number));
        singInfo.put("state","4");
        classMapper.addSingIn(singInfo);
    }
    /**
     * 根据sid获取用户的所有班级
     * @param openId
     * @return
     */
    @Override
    public JSONObject getUserJoinClass(String openId) {
        JSONObject result = new JSONObject();
        User user = userMapper.getUser(openId);

        //得到用户所有的班级操作
        List<ClassRecord> classList = userMapper.getUserJoinClass(user.getSid());

        result.put("classList",classList);
        return result;
    }

    @Override
    public JSONObject getUserInfo(String openId) {
        JSONObject result = new JSONObject();
        User user = userMapper.getUser(openId);

        result.put("sid",user.getSid());
        result.put("name",user.getName());
        result.put("url",user.getFace_url());

        return result;
    }

    @Override
    public boolean updateUserInfo(HashMap<String, String> userInfo) {
        return userMapper.updateUserInfo(userInfo)>0;
    }

    @Override
    public JSONObject   getConductInfo(String openId) {
        JSONObject result = new JSONObject();
        User user = userMapper.getUser(openId);

        //得到用户所有的班级操作
        List<ClassRecord> classList = userMapper.getUserJoinClass(user.getSid());

        for(ClassRecord classRecord:classList){
            String cid = classRecord.getCid();
            String key =redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid);
            JSONObject info = redisUtil.getJson(key);
            if(info!=null){
                result.put("type",info.getString("type"));
                result.put("time",info.getLongValue("time"));
                result.put("cid",cid);
                return result;
            }
        }
        return null;
    }

    @Override
    public boolean delClass(String openId,String cid) {
        User user = userMapper.getUser(openId);

        userMapper.delClass(user.getSid(),cid);
        return true;
    }

    @Override
    public boolean Test() {
        String time = DateTime.getTimestamp("YYYYMM");
        String table ="test_"+time;
        classMapper.test(table);

        return true;
    }


}
